################################# common ####################################

# 设置rm -f 指令不提示
setopt localoptions rmstarsilent

# 配置命令模糊匹配:
zstyle ':completion:*' matcher-list '' \
    'm:{a-z\-}={A-Z\_}' \
    'r:[^[:alpha:]]||[[:alpha:]]=** r:|=* m:{a-z\-}={A-Z\_}' \
    'r:|?=** m:{a-z\-}={A-Z\_}'

alias ka="killall"

# 杀死占用端口的进程:
kp() {
    if [ $# != 1 ]; then
        echo "#### 使用方法: kp 80"
        return
    fi
    port=$1
    kill -9 $(lsof -t -i:$port)
    # 如果是docker容器占用的端口，用上面的方法还不够:
    for name in $(docker ps --format "{{.Names}}"); do
        if [[ $(docker port "${name}") == *"${port}"* ]]; then
            echo "stopping container ${name}"
            docker stop "${name}"
        fi
    done
}

# 操作zshrc
alias venv="vim ~/.zshrc"
alias senv="source ~/.zshrc"

alias vhosts="sudo vim /etc/hosts"

alias ip='f() { curl http://checkip.amazonaws.com/ };f'
alias 777="chmod -Rv 777"
alias 755="chmod -Rv 755"
alias 644="chmod -Rv 644"
alias x="cdmod +x"

http2() {
    if [ $# != 1 ]; then
        python2 -m SimpleHTTPServer 80
        return
    fi
    python2 -m SimpleHTTPServer $1
}

http3() {
    if [ $# != 1 ]; then
        python3 -m http.server 80
        return
    fi
    python3 -m http.server $1
}

gs() {git add --all && git commit -m 'sync...' && git pull && git push}

alias c='clear'

# find:
alias ff='f() { find / -type f -name "$1" };f'
alias fd='f() { find / -type d -name "$1" };f'
alias fa='f() { find / -type d,f,l -name "$1" };f'

find_by_name() {
    find . -iname "$1"
}

alias aps='f() { ps -ef | grep $1 };f'
alias als='ls -lah'

# 进程相关：
k() {ps -ef | grep $1 | awk '{print $2}' | xargs kill -9}
d() {find . -name $1 -exec rm -rf {} \; >>/dev/null 2>&1} #递归删除目录下所有

# msyql:
# alias ml='f() { mysql -uroot -p\n };f'
alias ml='f() { mysql --auto-rehash -uroot -p\n };f'

# vim 设置高亮和显示行号：
vim_enable_highlight() {
    echo "set nu
    syntax on" >$HOME/.vimrc
}

proxy_set_http() {
    export https_proxy=http://"$1"
    export http_proxy=http://"$1"
}

proxy_set_socks() {
    all_proxy=socks5://"$1"
}

# youtube-dl相关:
# 下载指定格式：
# ydl(){
#     echo "yd 133 https://www.youtube.com/watch?v=6SwJpgNLvTk"
#     youtube-dl -f $1 $2
# }
# # 查看格式：
# ydlf(){
#     echo "ydf https://www.youtube.com/watch?v=6SwJpgNLvTk"
#     youtube-dl -F $1
# }

# 查看可下载格式:
alias ydf='youtube-dl -F' # ydf https://www.youtube.com/watch?v=6SwJpgNLvTk

# 下载单个视频: yd https://www.youtube.com/watch?v=a2K9MEkesto
alias yd="youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio' --merge-output-format mp4 --write-auto-sub --sub-lang en"

# 下载播放列表: ydl https://www.youtube.com/playlist?list=PLmwmigPkv3_AFMe0v13xmgjcRbmWr7qJ3
alias ydl="youtube-dl --yes-playlist -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio' --merge-output-format mp4 --write-auto-sub --sub-lang en"

# git:
alias gc='git clone'

# pipenv:
alias pvi='pipenv install'
alias pvs='pipenv sync'
alias pv='pipenv'
alias pvr='pipenv run'

# poetry:
alias poe='poetry'
alias poeinit='poetry init'
alias poeadd='poetry add'
alias poeremove='poetry remove'
alias poerun='poetry run'
alias poeinstall='poetry install'

# mitmproxy
alias mms='mitmdump -s'
alias mm='mitmdump'

# 安装：
install_air() {
    curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin
}

# 安装：
install_poetry() {
    curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -
}

# 设置path:
export PATH=$PATH:$HOME/.poetry/bin # poetry

install_odoo14_docker() {
    docker stop odoo
    docker rm odoo
    docker stop db
    docker rm db

    docker run -d -e POSTGRES_USER=odoo -e POSTGRES_PASSWORD=odoo -e POSTGRES_DB=postgres --name db postgres:10
    docker run -d -p 80:8069 --name odoo --link db:db --restart=always -it odoo
}

install_odoo13_docker() {
    docker stop odoo
    docker rm odoo
    docker stop db
    docker rm db

    docker run -d -e POSTGRES_USER=odoo -e POSTGRES_PASSWORD=odoo -e POSTGRES_DB=postgres --name db postgres:10
    docker run -d -p 80:8069 --name odoo --link db:db --restart=always -it odoo
}

# golang相关:
gg_private() {
    go get -u gitee.com/elonelon/go_pkg/chromedp-base
    go get -u gitee.com/elonelon/go_pkg/qywechat
    go get -u gitee.com/elonelon/go_pkg/websocket
    go get -u gitee.com/elonelon/go_pkg/webdav
    go get -u gitee.com/elonelon/go_pkg/util
}

gg_public() {
    go get -u github.com/chromedp/chromedp
    go get -u github.com/spf13/cobra
    go get github.com/robfig/cron/v3@v3.0.0
    go get -u github.com/gin-gonic/gin
    go get -u gorm.io/gorm
    go get -u gorm.io/driver/sqlite
    go get go.mongodb.org/mongo-driver/mongo
    go get -u github.com/go-sql-driver/mysql
    go get github.com/go-resty/resty/v2
    go get github.com/unrolled/secure
    go get github.com/mattn/go-sqlite3
    go get github.com/spf13/viper
}

gg_clean() {
    go clean -modcache
}

curl_only_response_headers() {
    curl -L -s -D - -o /dev/null $1
}

curl_only_response_cookies() {
    curl -L -s -c - -o /dev/null $1
}

curl_post() {
    echo ""
    curl $1 -X POST -d $2
}

curl_post_json() {
    # if [ $# != 2 ] ; then
    #     echo '#### 使用方法: curl_post_json http://xxx '{"userID":10001}'"
    #     return
    # fi

    url=$1
    data=$2

    curl -H "Content-Type: application/json" -X POST --data $data $url
}

chrome_start_remote_debug_docker() {
    docker stop headless-shell
    docker run -d -p 9222:9222 --rm --name headless-shell goybltpc/headless-shell
    # docker run -d -p 9222:9222 --rm --name headless-shell --shm-size 2G chromedp/headless-shell
}

chrome_stop_remote_debug_docker() {
    docker stop headless-shell
    docker rm headless-shell
}

kachrome() {
    killall Chromium
}

# redis-docker:
redis_start_container() {
    if [ $# != 3 ]; then
        echo "#### 使用方法: redis_start_container redis_tb 6381 password"
        return
    fi

    docker stop $1
    docker rm $1
    docker run --name $1 -p $2:6379 -d redis --requirepass $3 --appendonly yes
}

redis_stop_container() {
    if [ $# != 1 ]; then
        echo "#### 使用方法: redis_stop_container redis_test"
        return
    fi
    docker stop $1
    docker rm $1
}

redis_connect_container() {
    if [ $# != 2 ]; then
        echo "#### 使用方法: redis_connect_container 6381 pwd"
        return
    fi
    redis-cli -h localhost -p $1 -a $2
}

# mongo-docker:
mongo_stop_container() {
    if [ $# != 1 ]; then
        echo "#### 使用方法: mongo_stop_container mongo_test"
        return
    fi
    docker stop $1
    docker rm $1
}

mongo_start_container() {
    if [ $# != 2 ]; then
        echo "#### 使用方法: mongo_start_container mongo_test 27017"
        return
    fi
    # docker run --name $1 -d -p $2:27017 mongo mongod --auth

    docker stop $1
    docker rm $1
    docker run --name $1 -d -p $2:27017 -v /opt/docker/$1:/data/db mongo mongod
}

mongo_connect_container() {
    if [ $# != 1 ]; then
        echo "#### 使用方法: mongo_connect_container mongo_test"
        return
    fi
    docker exec -it $1 bash
}

# 未完成:
awk_replace_first_match() {
    if [ $# != 3 ]; then
        echo "#### 第一次匹配，后插入"
        echo "#### 使用方法: awk_replace_first_match line_to_find content_to_replace xxx.conf "
        return
    fi

    pattern=$1
    content_to_replace=$2
    file_name=$3

    awk '!x{x=sub("apple","banana")}7' file_name
}

awk_version() {
    awk -W version
}

awk_insert_after_first_match() {
    if [ $# != 3 ]; then
        echo "#### 第一次匹配，后插入"
        echo "#### 使用方法: awk_insert_after_first_match line_to_find content_to_insert xxx.conf "
        return
    fi

    pattern=$1
    content_to_insert=$2
    file_name=$3

    awk -v "content_to_insert=$content_to_insert" -v pattern="$pattern" '{print} $0~pattern && !n {print content_to_insert; n++}' $file_name >tmp && mv tmp $file_name
}

awk_insert_before_first_match() {
    if [ $# != 3 ]; then
        echo "#### 第一次匹配，前插入"
        echo "#### 使用方法: awk_insert_before_first_match line_to_find content_to_insert xxx.conf "
        return
    fi

    pattern=$1
    content_to_insert=$2
    file_name=$3

    awk -v "content_to_insert=$content_to_insert" -v pattern="$pattern" '$0~pattern && !x {print content_to_insert; x=1} 1' $file_name >tmp && mv tmp $file_name
}

nginx_list_conf() {
    echo "---------------------------"
    ls -d /etc/nginx/conf.d/*.conf
    echo "---------------------------"
    ls -d /etc/nginx/sites-enabled/*.conf
}

nginx_path() {
    echo "/etc/nginx/conf.d/*.conf"
    echo "/etc/nginx/nginx.conf"
    echo "/etc/nginx/sites-enabled/*.conf"
    cd /etc/nginx/conf.d/
}

nginx_del_all_conf() {
    rm "/etc/nginx/conf.d/*.conf"
    nginx -s reload
}

nginx_del_conf() {
    if [ $# != 1 ]; then
        echo "#### 使用方法: nginx_show_conf weixin.conf"
        return
    fi
    rm -rf /etc/nginx/conf.d/$1
    nginx -s reload
}

nginx_add_route() {
    if [ $# != 3 ]; then
        echo "#### 使用方法: nginx_add_route banli.site test 9999 "
        return
    fi

    host_name=$1
    path_name=$2
    port=$3

    file_name=/etc/nginx/conf.d/"$1".conf

    if [ ! -f "$file_name" ]; then
        cat >$file_name <<EOF

upstream $path_name {
    server localhost:$port;
}

server {
    listen 80;
    server_name $host_name;

    location ^~/$path_name/ {
        proxy_set_header Host host;
        proxy_set_header X-real-ip remote_addr;
        proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;

        proxy_pass http://$path_name/;
    }
}

EOF
    else
        location_to_insert="
    location ^~/$path_name/ {
        proxy_set_header Host host;
        proxy_set_header X-real-ip remote_addr;
        proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;

        proxy_pass http://$path_name/;
    }

        "
        awk_insert_after_first_match server_name $location_to_insert $file_name

        upstream_to_insert="

upstream $path_name {
    server localhost:$port;
}

        "
        awk_insert_before_first_match "upstream " $upstream_to_insert $file_name

    fi

    nginx -s reload

    cat $file_name

}

debian_set_alias() {
    tmp_dir="$HOME/.debian.sh"

    if [ -f $tmp_dir ]; then
        echo "success"
    else
        apt update
        apt install curl zsh -y
        chsh -s /bin/zsh
    fi

    curl -s https://gitee.com/elonelon/dotfiles/raw/master/alias/debian.sh >$tmp_dir
    curl -s https://gitee.com/elonelon/dotfiles/raw/master/alias/common.sh >>$tmp_dir
    sed -i "/.debian.sh/d" "$HOME"/.zshrc
    echo "source $tmp_dir" >>"$HOME/.zshrc"
    source "$HOME/.zshrc"
    curl -s https://gitee.com/elonelon/dotfiles/raw/master/vimrc >"$HOME"/.vimrc
}

alias cr="composer require"

random_string() {
    len=$1
    re='^[0-9]+$'
    if ! [[ $len =~ $re ]]; then
        echo "需要传入位数"
        return
    fi
    if ! which md5sum >/dev/null 2>&1; then
        if [ "$(uname)" == "Darwin" ]; then
            # macos
            echo "md5sum not installed, run 'brew install md5sha1sum' to install"
            return
        fi
    fi
    res=$(date +%s%N | md5sum | cut -c 1-$len)
    echo $res
}

# 会补齐:
random_number() {
    len=$1
    tmp=$(10*$len)
    printf "%0$len""d\n" $((1 + RANDOM % $tmp))
}

cls() {
    if [ $# != 1 ]; then
        ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
             *2^(8-i));if(k)printf("%0o ",k);print}'
        return
    else
        ls -l $1 | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
             *2^(8-i));if(k)printf("%0o ",k);print}'
    fi
}
